use crate::resolver::generator::generate_version;
use crate::resolver::Resolver;

impl Resolver {
    pub fn handle(&mut self) -> anyhow::Result<()> {
        let types = self.config.types.as_ref().unwrap();
        for version in &mut self.history.versions {
            for section in &mut version.sections {
                // 替换"break"为"重大更新"
                if let Some(t) = types.iter().find(|t| t.type_ == section.section) {
                    section.section = t.section.clone();
                }
                // 调整顺序
                if self.cli_args.rev_commit {
                    section.commits.reverse();
                }
            }
        }
        // 生成版本号
        generate_version(&self.cli_args, &mut self.history.versions)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::resolver::cli_args::CliArgs;
    use crate::utils::test_utils::{setup_with_commits_json, teardown_git};
    #[test]
    fn test_handle() -> anyhow::Result<()> {
        let test_folder = setup_with_commits_json("tests/test_commits/test1.json")?;
        let mut args = CliArgs::new();
        args.path = Some(test_folder.to_string());
        let mut resolver = Resolver::init(args)?;
        // 解析git历史
        resolver.resolve()?;
        assert_eq!(5, resolver.history.versions.len());
        assert_eq!(0, resolver.history.versions[0].sections.len());
        resolver.handle()?;
        assert!(resolver.history.versions[1].sections[0]
            .section
            .contains("新功能"));
        teardown_git(&test_folder);
        Ok(())
    }
}
